'use strict';

(function(){
  const SEL='li,.tile,.track,.row,.list-item,.item,.result,.result-item,.track-card';
  const ACTIVE=/匹配灵敏度|ΔE|用此颜色搜索音乐|吸管取色/.test(document.body.innerText||'');
  if(!ACTIVE) return;
  const audio=(()=>{ let el=document.getElementById('rt-preview'); if(!el){ el=document.createElement('audio'); el.id='rt-preview'; el.preload='none'; document.body.appendChild(el);} return el; })();
  const fav=new Set(JSON.parse(localStorage.getItem('rt_fav_tracks')||'[]')); function save(){ localStorage.setItem('rt_fav_tracks', JSON.stringify(Array.from(fav))); }
  function slug(s){ return (s||'').toLowerCase().replace(/\s+/g,'-').replace(/[^\w\-]+/g,'').replace(/\-\-+/g,'-').replace(/^-+|+-$/g,''); }
  function title(el){ let t=''; const c=el.querySelector('.title,.track-title,h3,h4,a,.name,.track-name'); if(c)t=c.textContent.trim(); if(!t){ const raw=(el.textContent||'').trim(); t=raw.split('·')[0]; } return t||'unknown-track'; }
  function preview(el){
    for(const k of['preview','audio','src','url']){ if(el.dataset && el.dataset[k]) return el.dataset[k]; }
    const p=el.querySelector('[data-preview],[data-audio],[data-src]'); if(p){
      for(const k of['preview','audio','src']){ if(p.dataset && p.dataset[k]) return p.dataset[k]; }
      const href=p.getAttribute && p.getAttribute('href'); if(href && /\.(mp3|wav|ogg)$/i.test(href)) return href;
    }
    const a=el.querySelector('audio[src]'); if(a) return a.getAttribute('src');
    return 'assets/previews/grey_minimal.wav';
  }
  function mount(row){
    if(row.classList.contains('rt-row')) return;
    const txt=row.textContent||''; if(!/#([0-9a-fA-F]{6})/.test(txt) || !/ΔE|DE\s*\d+/i.test(txt)) return;
    row.classList.add('rt-row');
    const bar=document.createElement('div'); bar.className='rt-actions';
    const b1=document.createElement('button'); b1.className='rt-btn rt-btn--ghost'; b1.textContent='试听';
    let playing=false; b1.addEventListener('click', function(e){ e.stopPropagation(); const url=preview(row); if(!playing){ audio.src=url; audio.play().catch(()=>{}); b1.textContent='暂停'; playing=true; } else { audio.pause(); b1.textContent='试听'; playing=false; } });
    audio.addEventListener('ended', ()=>{ b1.textContent='试听'; playing=false; });
    const b2=document.createElement('button'); b2.className='rt-btn rt-btn--solid'; b2.textContent='购买'; b2.addEventListener('click', function(e){ e.stopPropagation();
    var s = title(row);
    var hex=(new URLSearchParams(location.search).get('hex')||'').trim();
    if(!hex){ try{ hex=(JSON.parse(localStorage.getItem('rt_color_matches')||'{}').selectedHex)||''; }catch(err){} }
    var url='checkout.html?item='+encodeURIComponent(s)+(hex?('&hex='+encodeURIComponent(hex)):'');
    location.href = url;
  });
    const b3=document.createElement('button'); b3.className='rt-btn rt-btn--ghost rt-btn--fav'; b3.textContent='收藏';
    const key=slug(title(row)); if(fav.has(key)) b3.classList.add('is-active');
    b3.addEventListener('click', function(e){ e.stopPropagation(); if(fav.has(key)){ fav.delete(key); b3.classList.remove('is-active'); } else { fav.add(key); b3.classList.add('is-active'); } save(); });
    const prev=preview(row); const ext=(prev.split('.').pop()||'wav').toLowerCase();
    const b4=document.createElement('a'); b4.className='rt-btn rt-btn--ghost'; b4.textContent='下载'; b4.href=prev; b4.setAttribute('download', key+'.preview.'+ext);
    bar.appendChild(b1); bar.appendChild(b2); bar.appendChild(b3); bar.appendChild(b4); row.appendChild(bar);
  }
  function scan(){ document.querySelectorAll(SEL).forEach(mount); }
  if(document.readyState==='loading'){ document.addEventListener('DOMContentLoaded', scan); } else { scan(); }
  new MutationObserver(m=>{ for(const x of m){ if(x.addedNodes && x.addedNodes.length){ scan(); break; } } }).observe(document.body,{childList:true,subtree:true});
})();
